<template>
  <div class="atlas-intelligent-retrieval-wrapper" id="intelligent">
    <div v-show="showMain" class="template-wrapper">
      <div class="main-container" style="height: 100%;" id="mainCon">
        <!--  名称 -->
        <div class="wrapper-top">
          <div
            class="seek"
            @click="showMenu = !showMenu"
            v-show="showInputIcon"
          >
            <el-tooltip
              class="item"
              effect="light"
              content="点击选择探寻关系"
              placement="top-start"
            >
              <el-button class="seek-btn item"></el-button>
            </el-tooltip>
          </div>
          <el-tooltip
            class="item"
            effect="light"
            content="下载"
            placement="top-start"
            v-show="showInputIcon"
          >
            <el-dropdown
              trigger="click"
              class="download parentnode"
              placement="bottom"
            >
              <span class="el-dropdown-link item"></span>
              <el-dropdown-menu slot="dropdown" class="download-dropmenu">
                <el-dropdown-item @click.native="downloadOverall"
                  >导出全景图</el-dropdown-item
                >
                <el-dropdown-item @click.native="downloadCur"
                  >导出当前图</el-dropdown-item
                >
                <!-- <el-dropdown-item @click.native="manualRemarks"
                  >保存图谱</el-dropdown-item
                >
                <el-dropdown-item @click.native="showMyAltas"
                  >我的图谱</el-dropdown-item
                >
                <el-dropdown-item @click.native="exportExcel"
                  >导出Excel</el-dropdown-item
                > -->
              </el-dropdown-menu>
            </el-dropdown>
          </el-tooltip>
          <div class="search">
            <el-button
              v-show="showInputIcon"
              class="search-btn item"
              @click.stop="searchNode"
            ></el-button>
            <div
              id="searchWrapper"
              class="search-wrapper"
              :class="{ 'focus-input': isFocus }"
              v-show="!showInputIcon"
            >
              <!-- <el-autocomplete
                v-model="keyword"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                value-key="name"
                clearable
                @keyup.enter="handleSelect(keyword)"
                @focus="isFocus = true"
                @blur="isFocus = false"
                @select="handleSelect"
              > -->
              <el-autocomplete
                v-model="keyword"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                value-key="name"
                clearable
                @keyup.enter="handleSelect()"
                @focus="isFocus = true"
                @blur="isFocus = false"
                @select="handleSelect"
              >
                <template slot="prepend">
                  <i
                    class="el-input__icon icon-search"
                    @click="handleSelect(keyword)"
                  ></i>
                </template>
                <!-- <template slot="append">
                  <i class="el-input__icon icon-search" @click="handleSelect({name:keyword})"></i>
                </template> -->
              </el-autocomplete>
            </div>
          </div>
        </div>
        <!-- <div class="wrapper-main"> -->
        <div class="wrapper-bottom">
          <relationship-graph></relationship-graph>
        </div>
      </div>
      <left-menu
        v-if="showMenu"
        class="left-menu"
        ref="leftmenu"
        @collapseMenu="menuChange"
        @getFilter="getFilter"
        @seachNode="seachNode"
        :entityTypes="entityTypes"
        :nodeRelations="nodeRelations"
      ></left-menu>
    </div>
  </div>
</template>
<script>
import LeftMenu from "./model/LeftMenu.vue";
import MyGraph from "./model/MyGraph.vue";
import {
  RelationshipGraph,
  useGraph
} from "../../../components/other-extend-components/RelationshipGraph";
import nodeData from "./model/data.js";
import nodeLegend from './model/nodeLegend'
export default {
  name: "AtlasIntelligentRetrieval",
  mixins:[nodeLegend],
  components: {
    MyGraph,
    LeftMenu,
    RelationshipGraph
  },
  data() {
    let baseUrl = this.atlasRemoteUrl;
    return {
      urls: {
        fetchAltasUrl: baseUrl + "/weaponry/getNodes",
        fetchChildNodeUrl : baseUrl + "/general/getNextNodes",
        delNodeUrl: baseUrl + "/general/delete",
        updateNodeUrl: baseUrl + "/general/updateLabel",
        addNodeUrl: baseUrl + "/general/insertLabel",
        searchUrl: baseUrl + "/weaponry/findByName",
        typeUrl: baseUrl + "/general/getTypeAndNameCH",
        getRelationUrl: baseUrl + "/general/getRelationById",
        addRelationUrl: baseUrl + "/general/userAddRelation"
      },
      showMain: true,
      showAttr: false,
      corePath: false,
      keyEnt: false,
      keyPerson: false,
      highlightPath: false,
      shortPath: false,
      showRemark: false,
      noteName: "",
      showPanel: false,
      showMenu: false,
      showInputIcon: true,
      keyword: "",
      noteValue: "",
      param: {},
      relationGraph: null,
      countData: {},
      nodes: [],
      links: [],
      closeFun: null,
      listTableFilterData: {
        province: [],
        industryphy_cn: []
      },
      listtableParam: {},
      showNoteTip: false,
      entList: [],
      filters: {
      },
      canShowMyAltas: false,
      isFocus: false,
      spreadData: {},
      nodeIds: [],
      entityTypes:[],
      nodeRelations:[]
    };
  },
  mounted() {
    this.getType()
    this.showSearchBox();
    this.getAltas();
  },
  methods: {
    //  获取图谱的数据
    getAltas() {
      let _this = this;
      // let params = this.param;
      this.httpClient(this, {
        type: "get",
        url: this.urls.fetchAltasUrl,
        param: {},
        hideSuccessTip: true,
        ignoreEmptyData: true,
        fullSuccess: true,
        success: function(res) {
          let data = res.value;
          _this.relationGraph = useGraph({
            rootKey: data.nodes[0].id
          }).setOptions({
            ...nodeData,
            nodeCategories:[..._this.nodesLegend,...nodeData.nodeCategories],
            nodes: data.nodes,
            links: data.links.map(item=>({
              ...item,
              rid:item.source+','+item.target
            }))
          });
          _this.spreadEventListener();
          _this.retractEventListener()
          _this.addNode()
          _this.delNodes()
          _this.updateNode()
          _this.selectNode()
          _this.nodeIds = data.nodes.map(d=>d.id);
          _this.nodes = _this.cloneObj(data.nodes);
          _this.links = _this.cloneObj(data.links);
        },
        error: function( err){
           _this.relationGraph = useGraph({
            rootKey: nodeData.nodes[0].id
          }).setOptions({
            ...nodeData
          });
          _this.spreadEventListener();
          _this.retractEventListener()
          _this.addNode()
          _this.delNodes()
          _this.updateNode()
          _this.selectNode()
          _this.nodeIds = [];
          _this.nodes = _this.cloneObj(nodeData.nodes);
          _this.links = _this.cloneObj(nodeData.links);
        }
      });
    },
    //  监听图谱的展开事件
    spreadEventListener() {
      let _this = this,
        data = {};
      this.relationGraph.on("expand-node", async node => {
        await _this.spreadNode(node.type, node.id);
        data = _this.spreadData;
        _this.relationGraph.expandNode(node, {
          nodes:data.nodes,
          links:data.links.map( item => ({
            ...item,
            rid: item.source + ',' + item.target
          }))
        });
      });
    },
    //  收起节点
    retractEventListener() {
      let _this = this
      this.relationGraph.on("retract-node", node => {
        _this.relationGraph.retractNode(node);
      });
    },
    //  删除节点
    delNodes(){
      let _this = this
      this.relationGraph.on("del-node", node => {
        _this.httpClient(_this,{
          type:'post',
          url: _this.urls.delNodeUrl,
          param:{
            id:node.id
          },
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
          success: function(res) {

          }
        })
      })
    },
    //  修改
    updateNode(){
      let _this = this
      this.relationGraph.on('update-node',(node,data)=>{
        _this.httpClient(_this,{
          type: 'post',
          url: _this.urls.updateNodeUrl,
          param:{
            id:node.id,
            type:node.type,
            ...data
          },
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
          success: function(res) {
            //  是否修改成功的提示
          }
        })
      })
    },
    //  新增节点
    addNode(){
      let _this = this
      this.relationGraph.on("add-child", (parentNode, data) => {
        _this.httpClient(_this,{
          type:'post',
          url: _this.urls.addNodeUrl,
          param:{
            type: parentNode.type,
            oldId: parentNode.id,
            ...data
          },
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
          success: function(res) {
            //  新增节点的信息，设计到新增节点以及新增关系
            //  需要获取关系的类型，以及新增节点的类型
          }
        })
      })
    },
    //  选中节点
    selectNode(){
      let _this = this
      this.relationGraph.on("select-node", async (parentNode, nodes) => {
        await _this.getRelation(parentNode.id)
        _this.entityTypes = nodes.map( d => ({
            label: d.name,
            value: d.name
          }))
        _this.showMenu = true
        this.$nextTick(()=>{
          _this.$refs.leftmenu.reset()
        })
      })
    },
    //  新增节点之间的关系
    addRelation(){
      let _this = this
      this.relationGraph.on("add-relation", (node, relation)=>{
        // 添加二者之间的关系
        _this.httpClient(_this,{
          type:'post',
          url:_this.urls.addRelationUrl,
          param:{
            startName:"",
            endName:"",
            relation:""
          },
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
          success: function(res) {
            //  新增节点的信息，设计到新增节点以及新增关系
            //  需要获取关系的类型，以及新增节点的类型
          }
        })
      })
    },
    // 下钻的接口
    spreadNode(type, id) {
      let me = this
      return this.httpClient(this,{
        type:'post',
        url: this.urls.fetchChildNodeUrl,
        param: {
          id
        },
        hideSuccessTip: true,
        ignoreEmptyData: true,
        fullSuccess: true,
        success: function( res ){
          let data = res.value
          console.log(res);
          me.spreadData = data
          let newData = data.nodes.filter( d => !me.nodeIds.includes(d.id))
          me.nodes.push(newData)
          me.nodeIds.push(...(newData.map(d=>d.id)))
        }
      })
    },
    getFilter() {},
    //  处理搜索框的展示与隐藏
    showSearchBox() {
      let dom = document.getElementById("intelligent"),
        parentDom = document.getElementById("searchWrapper"),
        _this = this;
      //  如何关闭搜索框呢
      dom.addEventListener("click", e => {
        if (!parentDom.contains(e.target)) {
          _this.showInputIcon = true;
          _this.relationGraph.closeSearchMode()
          _this.keyword = ''
        }
      });
    },
    /**
     * 选中后去搜索
     */
    handleSelect(val) {
      this.relationGraph.searchNode(val.name);
      },
    //  全局搜索
    seachNode(name){
      // 搜索数据,重新获取nodes和links
      if(!name){
        this.getAltas()
      }
      let _this = this
      this.httpClient(this,{
        type:'post',
        url: this.urls.searchUrl,
        param:{
          name
        },
        hideSuccessTip: true,
        ignoreEmptyData: true,
        fullSuccess: true,
        success: function( res ){
          let data = res.value
          if(!data.nodes.length){
            _this.$message({
              type:'info',
              message:'无相关节点',
              duration: 1500
            })
            return
          }
          _this.relationGraph = useGraph({
            rootKey: data.nodes[0].id
          }).setOptions({
            ...nodeData,
            nodes: data.nodes,
            links: data.links.map(item=>({
              ...item,
              rid:item.source+','+item.target
            }))
          });
        }
      })
    },
    menuChange() {
      this.showMenu = !this.showMenu;
    },
    searchNode() {
      this.showInputIcon = false;
    },
    //  获取选中节点的关系
    getRelation(id){
      let _this = this
      return this.httpClient(_this,{
        type:'post',
        url: this.urls.getRelationUrl,
        param:{
          id
        },
        hideSuccessTip: true,
        ignoreEmptyData: true,
        fullSuccess: true,
        success: function(res) {
          //  新增节点的信息，设计到新增节点以及新增关系
          //  需要获取关系的类型，以及新增节点的类型
          let data = res.value
          _this.nodeRelations = data.map(d=>{
            return {
              label:d,
              value:d
            }
          })
        }
      })
    },
    //  导出全景图
    downloadOverall() {
      this.$nextTick(() => {
        this.relationGraph.exportPanorama();
      });
    },
    //  导出当前图
    downloadCur() {
      this.relationGraph.exportCurrentGraph();
    },
    // 打开我的图谱展示
    showMyAltas() {
      this.canShowMyAltas = true;
      this.$nextTick(() => {
        this.$refs.myGraph.getGrapth();
      });
    },
    querySearch(queryString, cb){
      let nodes = this.nodes;
      let results = queryString ? nodes.filter(this.createFilter(queryString)) : nodes;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (state) => {
        return (state.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
      };
    },
  }
};
</script>
<style lang="scss" scoped>
.atlas-intelligent-retrieval-wrapper {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 5px;
  .template-wrapper {
    width: 100%;
    height: 100%;
    position: relative;
  }
  .main-container {
    height: 100%;
    .wrapper-top {
      height: 50px;
      width: 100%;
      text-align: center;
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      a:hover:before {
        position: absolute;
        top: 20px;
        right: 0;
        content: attr(title);
        color: #000000;
        border: 1px solid #242424;
        background: #ffffff;
        border: 1px solid #303133;
      }
      .item {
        width: 42px;
        height: 42px;
        padding: 0;
        border-radius: 50%;
        box-shadow: 0 2px 12px 0 rgba(0, 21, 41, 0.2);
        margin-right: 10px;
      }
      .parentnode {
        padding: 0;
        border-radius: 50%;
        width: 42px;
        height: 42px;
        margin-right: 10px;
      }
      .note-tip {
        /deep/ .el-tooltip {
          border: none;
          &::before {
            display: inline-block;
            font-size: 24px;
            color: #fff;
          }
        }
      }
      .seek {
        .seek-btn {
          background: url("../../../assets/images/intelligentRetrieval/icon_seek.png")
            no-repeat;
          background-size: 100% 100%;
          border: none;
        }
      }
      .attribute {
        .el-dropdown-link {
          display: inline-block;
          background: url("../../../assets/images/intelligentRetrieval/icon_lujing.png")
            no-repeat;
          background-size: 100% 100%;
        }
      }
      .download {
        .el-dropdown-link {
          display: inline-block;
          background: url("../../../assets/images/intelligentRetrieval/icon_xiazai.png")
            no-repeat;
          background-size: 100% 100%;
        }
      }
      .search {
        width: 42px;
        height: 42px;
        position: relative;
        margin-right: 10px;
        .search-btn {
          background: url("../../../assets/images/intelligentRetrieval/icon_sousuo.png")
            no-repeat;
          background-size: 100% 100%;
          border: none;
        }
        .search-wrapper {
          position: absolute;
          left: -208px;
          width: 250px;
          height: 42px;
          &.focus-input {
            /deep/ .el-input {
              border: #2463b9 1px solid;
            }
          }
        }
        /deep/ .el-input {
          // position: absolute;
          background: #fff;
          border: transparent 1px solid;
          // left: -208px;
          width: 250px;
          height: 42px;
          border-radius: 21px;
          box-shadow: 0 0 5px rgba(0, 21, 41, 0.2);
          .el-input__inner {
            height: 100%;
            border: none;
            border-radius: 21px;
          }
          .el-input-group__prepend {
            width: 42px;
            padding: 0;
            border-radius: 50%;
            background: url("../../../assets/images/intelligentRetrieval/icon_sousuo.png")
              no-repeat;
            right: 0;
            border: none;
            cursor: pointer;
            .el-input-group__prepend {
              border: none;
            }
            .el-input__icon {
              width: 100%;
              display: inline-block;
            }
          }
          .el-input__suffix {
            padding-right: 8px;
            .el-input__icon {
              font-size: 18px;
              color: #909399;
            }
          }
        }
      }
      .risk-analysis {
        width: 276px;
        height: 42px;
        background: linear-gradient(left, #3b74fa 0%, #75a2f3 100%);
        border-radius: 21px;
        line-height: 42px;
        color: #fff;
        font-size: 16px;
        font-weight: bold;
        position: relative;
        box-shadow: 0 2px 12px 0 rgba(0, 21, 41, 0.2);
        cursor: pointer;
        .el-icon--right {
          position: absolute;
          right: 21px;
          top: 21px;
          font-weight: bold;
          transform: translateY(-50%);
        }
      }
    }
    .wrapper-top {
      height: 50px;
      width: 100%;
      text-align: center;
      //padding-top: 10px;
    }
    .wrapper-bottom {
      height: calc(100% - 60px);
      // padding: 20px;
    }
    .wrapper-main {
      width: 100%;
      height: calc(100% - 60px);
      .tree-chart {
        width: 100%;
        height: 100%;
      }
    }
  }
  .left-menu {
    width: 304px;
    // background: #fff;
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    z-index: 2;
  }
  .right-panel {
    position: absolute;
    right: 0;
    top: 0;
    z-index: 8;
  }
}
/deep/ .el-dropdown {
  color: #909399;
  background-color: #fff;
  height: 25px;
  width: 80px;
  border-radius: 4px;
  line-height: 25px;
  cursor: pointer;
}
/deep/.el-dropdown-menu {
  border: none;
  .attr-icon {
    display: inline-block;
    width: 0px;
    height: 16px;
    vertical-align: middle;
  }
  .popper__arrow::after {
    color: #fff;
  }
  .el-dropdown-menu__item {
    line-height: 44px;
    &:hover {
      color: #2463b9;
    }
  }
  &.download-dropmenu {
    padding: 4px 0;
    border: none;
  }
}
/deep/.attr-dropmenu {
  padding: 0;
  box-shadow: none;
  border: none !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
/deep/ .el-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #909399;
    color: #2463b9;
    .note-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }
  .el-dialog__body {
    padding-top: 15px;
    .el-textarea__inner {
      height: 100%;
    }
    .note-item {
      display: flex;
      margin-bottom: 16px;
      align-items: center;
      .note-label {
        width: 70px;
        vertical-align: middle;
      }
      .el-input,
      .el-textarea {
        width: calc(100% - 100px);
      }
    }
    .btns {
      text-align: center;
    }
    .bottom-tip {
      color: #606266;
      text-align: right;
      padding: 8px 16px 0;
    }
  }
}
</style>
